package barney.davis.hume.it3048todo;

import java.util.ArrayList;
import java.util.List;

import barney.davis.hume.it3048todo.constants.TaskStatus;
import barney.davis.hume.it3048todo.dao.ITaskDAO;
import barney.davis.hume.it3048todo.dao.TaskDAO;
import barney.davis.hume.it3048todo.dto.Task;
import barney.davis.hume.it3048todo.service.ITaskService;
import barney.davis.hume.it3048todo.service.TaskService;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

/**
 * @author Tony
 *
 */

public class ToDoList extends ListActivity {

	public static final String TASK_ID = "TASK_ID";
	
	private ListView listView;
	
	private String[] taskArray;
	
	private List<Task> tasks;
	
	final ITaskService taskService = new TaskService(this);

	
	class saveTasks implements Runnable {
		
		Task savingTask;
		public saveTasks(Task st)
		{
			savingTask = st;
		}
		@Override
		public void run() {
			 try {
			    	taskService.saveTask(savingTask);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		}
		
		
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		final ITaskService taskService = new TaskService(this);

		tasks = new ArrayList<Task>();
		
		try {
			tasks = taskService.getTasks(); 
		} catch (Exception e) {
			//to be changed to proper error
			Toast.makeText(ToDoList.this, e.getMessage(), Toast.LENGTH_LONG).show();
		}
		
		
		if(!tasks.isEmpty())
		{
			// Initialize the task array
			taskArray = new String[tasks.size()];
	
	        // Fill the songs array by using a for loop
	        for(int i=0; i < taskArray.length; i++){
	        	taskArray[i] = tasks.get(i).text;
	        }
	
			ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_multiple_choice, taskArray);
	
			listView = getListView();
			listView.setItemsCanFocus(false);
			listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			
			listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
	
				  @Override
				  public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				    Task selectedTask = tasks.get(position);
				    TaskStatus status;
				    
				    //Determine if checkbox should be checked
				    SparseBooleanArray checkedIds = listView.getCheckedItemPositions();
				    if(checkedIds.get(position))
				    {
				    	status = TaskStatus.COMPLETE;
				    }
				    else
				    {
				    	status = TaskStatus.INPROGRESS;
				    }
				    
				    selectedTask.setStatus(status);
				    
				    try {
					    saveTasks st = new saveTasks(selectedTask);
						Thread stThread = new Thread(st);
						stThread.start();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				  }
				});
			
			listView.setOnItemLongClickListener(new OnItemLongClickListener() {
				public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
					ITaskDAO taskDAO = new TaskDAO(parent.getContext());
	
					tasks = new ArrayList<Task>();
					
					try {
						tasks.addAll(taskDAO.fetchAll());
					} catch (Exception e) {
						//to be changed to proper error
						Toast.makeText(ToDoList.this, e.getMessage(), Toast.LENGTH_LONG).show();
	
					}
					
					// Find the task that the user selected.
					Task selectedTask = tasks.get(position);
			
					// create an intent to navigate to the task details page.
					Intent taskEditIntent = new Intent(ToDoList.this, AddTaskActivity.class);
					taskEditIntent.removeExtra(TASK_ID);
					taskEditIntent.putExtra(TASK_ID, selectedTask.ID);
			
					startActivity(taskEditIntent);
					return false;
				    
				  }
				});
			
			// show the data.
			setListAdapter(listAdapter);
			
			for (int i = 0; i < listAdapter.getCount(); i++) {
				if (tasks.get(i).status == TaskStatus.COMPLETE)
				{
					listView.setItemChecked(i, true);
				}
				else
				{
					listView.setItemChecked(i, false);
				}
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.to_do_list, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		//respond to menu item selection
		switch (item.getItemId()) {
		    case R.id.add_task:
		    	Intent taskAddIntent = new Intent(ToDoList.this, AddTaskActivity.class);
		    	startActivity(taskAddIntent);
		    return true;
		    case R.id.review:
		    	Intent reviewIntent = new Intent(ToDoList.this, ReviewActivity.class);
		    	startActivity(reviewIntent);
		    return true;
		    default:
		    return super.onOptionsItemSelected(item);
		}
	    
	}
}
